<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/27
 * Time: 14:44
 */

namespace App\Rep;


use App\Events\OrderEvent;
use App\Models\BalanceHistory;
use App\Models\CheckLog;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\FinishProduct;
use App\Models\Order;
use App\Models\OrderKucunLog;
use App\Models\OrderLogistics;
use App\Models\SemiFinishProduct;
use App\Models\StockAllocationLog;
use Illuminate\Support\Facades\DB;
use Cisco\Aliyunsms\Facades\Aliyunsms;
use Illuminate\Support\Facades\Log;

class FinishProductRep
{

    /**
     * 获取成品列表
     * 物流状态1：待发货2未发货3已发货4部分待发货5部分未发货
     * @param $params
     */
    public function getFinishProductListRep($params){
        $model = FinishProduct::Search($params)
            ->where('is_stock_up',2)
            ->with(['order','stock_allocation_log','warehouse','order_logistics',
                'semi_finish_product'=>function($q){
                    $q->with(['models','product','specification','model_number','color']);
                },
                'image1'=>function($q){
                return $q->select('id','file_name','file_url');
            },'image2'=>function($q){
                return $q->select('id','file_name','file_url');
            },'image3'=>function($q){
                return $q->select('id','file_name','file_url');
            },'image4'=>function($q){
                return $q->select('id','file_name','file_url');
            }]);
        $order_type = $params['order_type']??'logistics_product';
        if($order_type != 'finish_product'){
            $list = $model
                //->orderByRaw("FIELD(logistics_status, " . implode(", ", [1, 4, 2, 5,3]) . ")")
                ->orderByRaw("FIELD(logistics_status, 1, 4, 2, 5,3)")
                ->paginate($params['per_page']??10);
        }else{
            $list = $model
                //->orderBy('warehouse_entry_time','desc')
                ->where('logistics_status','<>',3)
                ->orderByRaw("FIELD(logistics_status, 1, 4, 2, 5,3)")
                ->paginate($params['per_page']??10);
        }
        return $list;
    }

    /**
     * 获取备货列表
     */
    public function getStockUpListRep($params){
        $list = FinishProduct::Search($params)->where('is_stock_up',1)
            ->with(['order','stock_allocation_log','warehouse','goods_shelf'])
            ->orderBy('id','desc')->paginate($params['per_page']??10);
        return $list;
    }

    /**
     * 获取当前成品可调货列表
     * @param $params
     */
    public function getStockAllocationListRep($params){
        $finishProduct = FinishProduct::where('id',$params['id'])->first();
        $order = Order::where('id',$finishProduct->order_id)->first();
        $list = Order::where('model_number_id',$order->model_number_id)
            ->where('specification_id',$order->specification_id)
            ->where('color_id',$order->color_id)
            ->where(function($q)use($order){
                if(!$order->direction){
                    $q->where('direction','')
                        ->orWhere(function($query){
                            $query->whereNull('direction');
                        });
                }else{
                    $q->where('direction',$order->direction);
                }
            })
            ->where('customer_id','<>',$order->customer_id)
            ->where('production_status',1)
            ->with(['customer'])
            ->paginate($params['per_page']??10);
        //p($list);
        return $list;
    }

    /**
     * 调货
     * @param $params
     */
    public function stockAllocationRep($params){
        DB::beginTransaction();
        try{
            $order = Order::where('id',$params['order_id'])->with('customer')->first();
            $finish_product = FinishProduct::where('id',$params['finish_product_id'])->first();
            $finish_order = Order::where('id',$finish_product->order_id)->first();
            //添加调货记录
            StockAllocationLog::Create([
                'finish_product_id'=>$finish_product->id,
                'order_id'=>$order->id,
//                'finish_customer_name'=>$finish_product->customer->customer_name,
//                'order_customer_name'=>$order->customer->customer_name,
                //'order_number'=>$order->order_number,
                'order_remark'=>$order->remark,
                'finish_order_remark'=>$finish_order->remark,
                'finish_order_id'=>$finish_product->order_id
            ]);
            $order_customer_id = $order->customer_id;
            $finish_product_customer_id = $finish_order->customer_id;
            $order->customer_id = $finish_product_customer_id;
            $order->remark = $finish_order->remark;
            $order->save();
            $finish_order->customer_id = $order_customer_id;
            $finish_order->remark = $order->remark;
            $finish_order->save();
            $finish_product->customer_id = $order_customer_id;
            $finish_product->save();
            DB::commit();
            return ['code'=>0,'msg'=>'success','data'=>[]];

        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'msg'=>$exception->getMessage(),'data'=>[]];
        }
    }

    /**
     * 获取调货记录
     */
    public function getStockAllocationLogRep($params){
        $list = StockAllocationLog::where('finish_product_id',$params['finish_product_id'])
            ->with(['order'=>function($q){
                $q->with('customer');
            },'finish_order'=>function($q){
                $q->with('customer');
            }])
            ->get();
        return $list;
    }


    /**
     * 设置待发货
     * 设置发货状态
     * 物流状态1：待发货2未发货3已发货4部分待发货5部分未发货
     * @param $params
     */
     public function setDeliveryStatusRep($params){
         $ids = $params['ids'];
         $num = $params['num']??'';
         $remark = $params['remark']??'设置待发货备注';
         DB::beginTransaction();
         try{
             if(!empty($num)){
                 $finishProduct = FinishProduct::where('id',$ids[0])->first();

                 //待发件数
                 $to_be_sent_num = $finishProduct->to_be_sent_num + $num;
                 if($to_be_sent_num + $finishProduct->sent_num == $finishProduct->num){
                     if($finishProduct->sent_num == 0){
                         $logistics_status = 1;//待发货
                     }else{
                         $logistics_status = 4;//部分待发货
                     }
                 }else{
                     $logistics_status = 4;//部分待发货
                 }
                 $finishProduct->logistics_status = $logistics_status;
                 $finishProduct->to_be_sent_num = $to_be_sent_num;
                 $finishProduct->save();
                 //添加发货记录
                 $orderLogisticsRep = new OrderLogisticsRep();
                 $orderLogistics[] = $orderLogisticsRep->addOrderLogistics($finishProduct->id,$finishProduct->order_id,3,$num,$remark);
             }else{
                 foreach($ids as $k=>$v){
                     $finishProduct = FinishProduct::where('id',$v)->first();
                     $num = $finishProduct->num - $finishProduct->sent_num - $finishProduct->to_be_sent_num;
                     $finishProduct->to_be_sent_num = $finishProduct->num - $finishProduct->sent_num;
                     $finishProduct->logistics_status = 1;
                     $finishProduct->save();
                     if($num > 0){
                         $orderLogisticsRep = new OrderLogisticsRep();
                         $orderLogistics[] = $orderLogisticsRep->addOrderLogistics($finishProduct->id,$finishProduct->order_id,3,$num,$remark);
                     }
                 }
             }
             DB::commit();
             return ['code'=>0,'data'=>$orderLogistics,'msg'=>'success'];
         }catch(\Exception $exception){
             DB::rollBack();
             return ['code'=>1001,'data'=>[],'msg'=>$exception->getMessage()];
         }

     }

    /**
     * 发货
     * @param $params
     * 物流状态1：待发货2未发货3已发货4部分待发货5部分未发货
     */
//     public function DeliverGoodsRep($params){
//         Log::channel('fahuolog')->info("++++++++++开始=========");
//         $finish_product_id = $params['finish_product_id'];
//         Log::channel('fahuolog')->info('成品id：'.$finish_product_id);
//         $order_logistics_id = $params['order_logistics_id'];
//         Log::channel('fahuolog')->info('物流记录id：'.$order_logistics_id);
//         if(!empty($params['remark'])){
//             $remark = $params['remark'];
//         }
//         $logistics_status = $params['logistics_status'];
//         $logistics_info = $params['logistics_info'];
//         DB::beginTransaction();
//         try{
//             $orderLogisticsRep = new OrderLogisticsRep();
//             $OrderLogistics = OrderLogistics::find($order_logistics_id);
//             //更新成品物流信息
//             $model = FinishProduct::where('id',$finish_product_id)->with(['order'=>function($q){
//                 $q->select('id','receivables','received');
//             }])->first();
//             if($OrderLogistics->logistics_status == 3){
//                 //更新物流信息
//                 $OrderLogistics = $orderLogisticsRep->updateOrderLogistics($order_logistics_id,$logistics_status,$logistics_info,$remark='');
//                 Log::channel('fahuolog')->info('更新后的物流信息：'.json_encode($OrderLogistics->toArray()));
//                 //更新后的已发件数
//                 $sent_num = $model->sent_num+$OrderLogistics->sent_num;
//                 Log::channel('fahuolog')->info('更新后的已发件数：'.$sent_num);
//                 //更新后的待发件数
//                 $to_be_sent_num = $model->to_be_sent_num - $OrderLogistics->sent_num;
//                 Log::channel('fahuolog')->info('更新后的待发件数：'.$to_be_sent_num);
//                 $model->sent_num = $sent_num;//已发件数
//                 $model->to_be_sent_num = $to_be_sent_num;
//                 if($model->num == $sent_num){
//                     $model->logistics_status = 3;//已发货
//                 }else{
//                     $model->logistics_status = 4;//部分已发货
//                     if($to_be_sent_num == 0){
//                         $model->logistics_status = 5;
//                     }
//                 }
//                 $model->delivery_time = $OrderLogistics->delivery_time;
//                 if(!empty($model->logistics_info)){
//                     $logistics_info = $model->logistics_info."|".$OrderLogistics->logistics_info;
//                 }else{
//                     $logistics_info = $OrderLogistics->logistics_info;
//                 }
//                 $model->logistics_info = $logistics_info;
//                 $model->save();
//             }else{
//                 Log::channel('fahuolog')->info('物流ID：'.$order_logistics_id."已发货不需要更新");
//             }
//
//
//             //发短信
//             if($params['duanxin']){
//                 $info = $this->getFinishProductInfoRep($params['id']);
//                 $res = $this->sendSMS($info);
//                 if($res['code'] != 0){
//                     return $res;
//                 }
//             }
//             //event(new OrderEvent($info));
//             Log::channel('fahuolog')->info('更新后的成品信息：'.json_encode($model->toArray()));
//             Log::channel('fahuolog')->info("++++++++++结束=========");
//             DB::commit();
//             return $model;
//         }catch(\Exception $exception){
//             DB::rollBack();
//             return ['code'=>1001,'data'=>[],'msg'=>$exception->getMessage()];
//         }
//     }
    public function DeliverGoodsRep($params){
         $finish_product_id = $params['finish_product_id'];
         $order_logistics_id = $params['order_logistics_id'];
         $remark = $params['remark'];
         $logistics_status = $params['logistics_status'];
         $logistics_info = $params['logistics_info'];
         $duanxin = $params['duanxin'];
         return $this->DeliverGoodsRepRep($finish_product_id,$order_logistics_id,$remark,$logistics_status,$logistics_info,$duanxin);
    }

    public function DeliverGoodsRepRep($finish_product_id,$order_logistics_id,$remark,$logistics_status,$logistics_info,$duanxin){
            $orderLogisticsRep = new OrderLogisticsRep();
            $OrderLogistics = OrderLogistics::find($order_logistics_id);
            //更新成品物流信息
            $model = FinishProduct::where('id',$finish_product_id)->with(['order'=>function($q){
                $q->select('id','receivables','received');
            }])->first();
            if($OrderLogistics->logistics_status == 3){
                //更新物流信息
                $OrderLogistics = $orderLogisticsRep->updateOrderLogistics($order_logistics_id,$logistics_status,$logistics_info,$remark);
                Log::channel('fahuolog')->info('更新后的物流信息：'.json_encode($OrderLogistics->toArray()));
                //更新后的已发件数
                $sent_num = $model->sent_num+$OrderLogistics->sent_num;
                Log::channel('fahuolog')->info('更新后的已发件数：'.$sent_num);
                //更新后的待发件数
                $to_be_sent_num = $model->to_be_sent_num - $OrderLogistics->sent_num;
                Log::channel('fahuolog')->info('更新后的待发件数：'.$to_be_sent_num);
                $model->sent_num = $sent_num;//已发件数
                $model->to_be_sent_num = $to_be_sent_num;
                if($model->num == $sent_num){
                    $model->logistics_status = 3;//已发货
                }else{
                    $model->logistics_status = 4;//部分已发货
                    if($to_be_sent_num == 0){
                        $model->logistics_status = 5;
                    }
                }
                $model->delivery_time = $OrderLogistics->delivery_time;
                if(!empty($model->logistics_info)){
                    $logistics_info = $model->logistics_info."|".$OrderLogistics->logistics_info;
                }else{
                    $logistics_info = $OrderLogistics->logistics_info;
                }
                $model->logistics_info = $logistics_info;
                $model->save();
            }else{
                Log::channel('fahuolog')->info('物流ID：'.$order_logistics_id."已发货不需要更新");
            }


            //发短信
            if($duanxin){
                $info = $this->getFinishProductInfoRep($finish_product_id);
                $res = $this->sendSMS($info);
                if($res['code'] != 0){
                    return $res;
                }
            }
            //event(new OrderEvent($info));
            Log::channel('fahuolog')->info('更新后的成品信息：'.json_encode($model->toArray()));
            Log::channel('fahuolog')->info("++++++++++结束=========");
            return $model;
    }



    /**
     * 扫码发货
     * @param $info
     * @return array
     */
    public function deliveryByScanningCodeRep($params){
        if(!empty($params['remark'])){
            $remark = $params['remark'];
        }
        $logistics_status = $params['logistics_status'];
        $logistics_info = $params['logistics_info'];
        $duanxin = $params['duanxin'];
        $finish = FinishProduct::where('order_id',$params['order_id'])->where('is_del',2)->first();
        if(!$finish){
            return ['code'=>2000,'data'=>[],'msg'=>'订单不存在或已删除'];
        }
        DB::beginTransaction();
        try{
            if($finish->logistics_status == 1){
                //待发货：直接发货
                $params_data = [];
                $orderLogisticsList = OrderLogistics::where('order_id',$params['order_id'])->get();
                foreach($orderLogisticsList as $k=>$v){
                    $params_data[] = [
                        'finish_product_id' => $finish->id,
                        'order_logistics_id' => $v->id,
                    ];
                    $finish = $this->DeliverGoodsRepRep($finish->id,$v->id,$remark,$logistics_status,$logistics_info,$duanxin);
                }

                DB::commit();
                return ['code'=>0,'data'=>$finish,'msg'=>'success'];
            }elseif($finish->logistics_status == 2){
                //未发货：直接设置为待发货，然后发货
                $finish->logistics_status = 1;
                $finish->to_be_sent_num = $finish->num;
                $finish->save();
                //添加发货记录
                $orderLogisticsRep = new OrderLogisticsRep();
                $remark = '未发货，扫码发货';
                $orderLogistics = $orderLogisticsRep->addOrderLogistics($finish->id,$finish->order_id,3,$finish->num,$remark);
                $params_data[] = [
                    'finish_product_id' => $finish->id,
                    'order_logistics_id' => $orderLogistics->id,
                ];
                $finish = $this->DeliverGoodsRepRep($finish->id,$orderLogistics->id,$remark,$logistics_status,$logistics_info,$duanxin);
                DB::commit();
                return ['code'=>0,'data'=>$finish,'msg'=>'success'];
            }elseif($finish->logistics_status == 3){
                //已发货
                $params_data = [];
                $orderLogisticsList = OrderLogistics::where('order_id',$params['order_id'])->get();
                foreach($orderLogisticsList as $k=>$v){
                    $params_data[] = [
                        'finish_product_id' => $finish->id,
                        'order_logistics_id' => $v->id,
                    ];
                    $finish = $this->DeliverGoodsRepRep($finish->id,$v->id,$remark,$logistics_status,$logistics_info,$duanxin);
                }

                DB::commit();
                return ['code'=>0,'data'=>$finish,'msg'=>'当前订单为已发货状态，请核对信息'];
            }elseif($finish->logistics_status == 4){
                //部分待发货
                $to_be_sent_num = $finish->num-$finish->to_be_sent_num-$finish->sent_num;
                if($finish->sent_num == 0){
                    $finish->logistics_status = 1;
                }else{
                    $finish->logistics_status = 4;
                }
                $finish->to_be_sent_num = $finish->num-$finish->sent_num;
                $finish->save();
                $params_data = [];
                //添加发货记录
                $orderLogisticsRep = new OrderLogisticsRep();
                $remark = '部分待发货，扫码发货';
                $orderLogisticsRep->addOrderLogistics($finish->id,$finish->order_id,3,$to_be_sent_num,$remark);
                $orderLogisticsList = OrderLogistics::where('order_id',$params['order_id'])->get();
                foreach($orderLogisticsList as $k=>$v){
                    $params_data[] = [
                        'finish_product_id' => $finish->id,
                        'order_logistics_id' => $v->id,
                    ];
                    $finish = $this->DeliverGoodsRepRep($finish->id,$v->id,$remark,$logistics_status,$logistics_info,$duanxin);
                }
                DB::commit();
                return ['code'=>0,'data'=>$finish,'msg'=>'success'];
            }elseif($finish->logistics_status == 5){
                //部分已发货
                $to_be_sent_num = $finish->num-$finish->sent_num-$finish->to_be_sent_num;
                $finish->to_be_sent_num = $to_be_sent_num;
                $finish->save();
                $params_data = [];
                //添加发货记录
                if($to_be_sent_num > 0){
                    $orderLogisticsRep = new OrderLogisticsRep();
                    $remark = '部分未发货，扫码发货';
                    $orderLogisticsRep->addOrderLogistics($finish->id,$finish->order_id,3,$to_be_sent_num,$remark);
                    $orderLogisticsList = OrderLogistics::where('order_id',$params['order_id'])->where('logistics_status',3)->get();
                    foreach($orderLogisticsList as $k=>$v){
                        $params_data[] = [
                            'finish_product_id' => $finish->id,
                            'order_logistics_id' => $v->id,
                        ];
                        $finish = $this->DeliverGoodsRepRep($finish->id,$v->id,$remark,$logistics_status,$logistics_info,$duanxin);
                    }
                }
                DB::commit();
                return ['code'=>0,'data'=>$finish,'msg'=>'success'];
            }
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>1001,'data'=>[],'msg'=>$exception->getMessage()];
        }
    }
//    public function deliveryByScanningCodeRep($params){
//        $finish = FinishProduct::where('order_id',$params['order_id'])->where('is_del',2)->first();
//        if(!$finish){
//            return ['code'=>2000,'data'=>[],'msg'=>'订单不存在或已删除'];
//        }
//        DB::beginTransaction();
//        try{
//            if($finish->logistics_status == 1){
//                //待发货：直接发货
//                $params_data = [];
//                $orderLogisticsList = OrderLogistics::where('order_id',$params['order_id'])->get();
//                foreach($orderLogisticsList as $k=>$v){
//                    $params_data[] = [
//                        'finish_product_id' => $finish->id,
//                        'order_logistics_id' => $v->id,
//                    ];
//                }
//                DB::commit();
//                return ['code'=>0,'data'=>$params_data,'msg'=>'success'];
//            }elseif($finish->logistics_status == 2){
//                //未发货：直接设置为待发货，然后发货
//                $finish->logistics_status = 1;
//                $finish->to_be_sent_num = $finish->num;
//                $finish->save();
//                //添加发货记录
//                $orderLogisticsRep = new OrderLogisticsRep();
//                $remark = '未发货，扫码发货';
//                $orderLogistics = $orderLogisticsRep->addOrderLogistics($finish->id,$finish->order_id,3,$finish->num,$remark);
//                $params_data[] = [
//                    'finish_product_id' => $finish->id,
//                    'order_logistics_id' => $orderLogistics->id,
//                ];
//                DB::commit();
//                return ['code'=>0,'data'=>$params_data,'msg'=>'success'];
//            }elseif($finish->logistics_status == 3){
//                //已发货
//                $params_data = [];
//                $orderLogisticsList = OrderLogistics::where('order_id',$params['order_id'])->get();
//                foreach($orderLogisticsList as $k=>$v){
//                    $params_data[] = [
//                        'finish_product_id' => $finish->id,
//                        'order_logistics_id' => $v->id,
//                    ];
//                }
//                DB::commit();
//                return ['code'=>0,'data'=>$params_data,'msg'=>'当前订单为已发货状态，请核对信息'];
//            }elseif($finish->logistics_status == 4){
//                //部分待发货
//                $to_be_sent_num = $finish->num-$finish->to_be_sent_num-$finish->sent_num;
//                if($finish->sent_num == 0){
//                    $finish->logistics_status = 1;
//                }else{
//                    $finish->logistics_status = 4;
//                }
//                $finish->to_be_sent_num = $finish->num-$finish->sent_num;
//                $finish->save();
//                $params_data = [];
//                //添加发货记录
//                $orderLogisticsRep = new OrderLogisticsRep();
//                $remark = '部分待发货，扫码发货';
//                $orderLogisticsRep->addOrderLogistics($finish->id,$finish->order_id,3,$to_be_sent_num,$remark);
//                $orderLogisticsList = OrderLogistics::where('order_id',$params['order_id'])->get();
//                foreach($orderLogisticsList as $k=>$v){
//                    $params_data[] = [
//                        'finish_product_id' => $finish->id,
//                        'order_logistics_id' => $v->id,
//                    ];
//                }
//                DB::commit();
//                return ['code'=>0,'data'=>$params_data,'msg'=>'success'];
//            }elseif($finish->logistics_status == 5){
//                //部分已发货
//                $to_be_sent_num = $finish->num-$finish->sent_num-$finish->to_be_sent_num;
//                $finish->to_be_sent_num = $to_be_sent_num;
//                $finish->save();
//                $params_data = [];
//                //添加发货记录
//                if($to_be_sent_num > 0){
//                    $orderLogisticsRep = new OrderLogisticsRep();
//                    $remark = '部分未发货，扫码发货';
//                    $orderLogisticsRep->addOrderLogistics($finish->id,$finish->order_id,3,$to_be_sent_num,$remark);
//                    $orderLogisticsList = OrderLogistics::where('order_id',$params['order_id'])->where('logistics_status',3)->get();
//                    foreach($orderLogisticsList as $k=>$v){
//                        $params_data[] = [
//                            'finish_product_id' => $finish->id,
//                            'order_logistics_id' => $v->id,
//                        ];
//                    }
//                }
//
//
//
//                DB::commit();
//                return ['code'=>0,'data'=>$params_data,'msg'=>'success'];
//            }
//        }catch(\Exception $exception){
//            DB::rollBack();
//            return ['code'=>1001,'data'=>[],'msg'=>$exception->getMessage()];
//        }
//    }


    /**
     * 取消待发货
     * 1：待发货2未发货3已发货4部分待发货5部分未发货
     */
    public function cancelDeliveryRep($params){
        $order_id = $params['order_id'];
        DB::beginTransaction();
        try{
            $finish = FinishProduct::where('order_id',$order_id)->first();
            if(in_array($finish->logistics_status,[1,4])){
                $finish->sent_num = 0;
                $finish->to_be_sent_num = 0;
                $finish->logistics_status = 2;
                $finish->save();
                OrderLogistics::where('order_id',$order_id)->delete();
            }

            DB::commit();
            return ['code'=>0,'data'=>$finish,'msg'=>'success'];
        }catch (\Exception $exception){
            DB::rollBack();
            return ['code'=>1001,'data'=>[],'msg'=>$exception->getMessage()];
        }
    }


    public function sendSMS($info)
    {
        //发送物流通知短信
        $SignName    = env('ALIYUN_SIGN_NAME');          //模板签名
        $TemplateCode= env('ALIYUN_TEMPLATECODE');         //模板CODE
        $customer_name = $info->order->customer->customer_name;
        $product_name = $info->order->product_name->product_name;
        $model_number = $info->order->model_number_name->model_number;
        $delivery_time = $info->delivery_time??date("Y-m-d H:i:s");
        $logistics_info = $info->logistics_info??123456;
        $phone = $info->order->customer->contact_phone;
        //$phone = '15135970424';
        //阿里云模板里面的变量
        $TemplateParam = [
            "customer_name"    => $customer_name,
            "product_name"     => $product_name,
            "model_number"     => $model_number,
            "delivery_time"    => $delivery_time,
            "logistics_info"   => $logistics_info
        ];
        //p($TemplateParam);

        $send = Aliyunsms::sendSms(strval($phone), $SignName, $TemplateCode, $TemplateParam);
        //p($send);
        if ($send->Code == 'OK') {
            $res = ['code'=>0,'msg'=>'success','data'=>''];
        } else {
            $res = ['code'=>3004,'msg'=>$send->Message,'data'=>$send];
        }
        return $res;
    }


    /**
     * 加入成品库
     * @param $order_id
     * @param $semi_finish_product_id
     * @param $num
     * @param $warehouse_id
     * @param $goods_shelf_id
     * @param $model_number_id
     * @param $specification_id
     * @param $color_id
     * @param $direction
     * @param $customer_id
     * @param $is_stock_up
     */
     public function addFinishProductRep($order_id,$warehouse_id,$goods_shelf_id,$model_number_id,$specification_id,$color_id,$customer_id,$is_stock_up,$num,$image_arr = []){
         $obj = FinishProduct::updateOrCreate(['order_id'=>$order_id],
             [
                 'order_id'=> $order_id,
                 'warehouse_id'=>$warehouse_id,
                 'goods_shelf_id'=>$goods_shelf_id,
                 'model_number_id'=>$model_number_id,
                 'specification_id'=>$specification_id,
                 'color_id' => $color_id,
                 'customer_id'=>$customer_id,
                 'warehouse_entry_time'=>date("Y-m-d"),
                 'is_stock_up'=>$is_stock_up,
                 'num'=>$num,
                 'image1'=>$image_arr[0]??null,
                 'image2'=>$image_arr[1]??null,
                 'image3'=>$image_arr[2]??null,
                 'image4'=>$image_arr[3]??null,
             ]
         );
         return $obj->id;
     }

    /**
     * 设置备货状态
     * @param $params
     */
     public function setStockUpStatusRep($params){
         DB::beginTransaction();
         try{
             $finish = FinishProduct::where('id',$params['id'])->first();
             $finish->is_stock_up = $params['is_stock_up'];
             $finish->customer_id = $params['customer_id']??0;
             $finish->save();
             $order = Order::where('id',$params['order_id'])->first();
             $order->is_stock_up = $params['is_stock_up'];
             $order->customer_id = $params['customer_id']??0;
             $order->save();
             DB::commit();
             return ['code'=>0,'msg'=>'success','data'=>[]];

         }catch(\Exception $exception){
             DB::rollBack();
             return ['code'=>2001,'msg'=>$exception->getMessage(),'data'=>[]];
         }

     }

    /**
     * 加入备货库
     * @param $params
     * @return void
     */
     public function finishAddSemiRep($params){
         DB::beginTransaction();
         try{
             $finish = FinishProduct::where('id',$params['finish_id'])->first();
             //$finish->is_del = 1;
             $finish->is_stock_up = 1;
             $finish->customer_id = 0;
             $finish->save();
             $semi_list = SemiFinishProduct::where('finish_id',$params['finish_id'])->get();
             foreach($semi_list as $k=>$v){
                 $v->finish_id = '';
                 $v->is_del = 2;
                 $v->warehouse_id = $params['warehouse_id'];
                 $v->save();
             }
             OrderKucunLog::where('order_id',$finish->order_id)->delete();
             DB::commit();
             return ['code'=>0,'msg'=>'success','data'=>[]];

         }catch(\Exception $exception){
             DB::rollBack();
             return ['code'=>2001,'msg'=>$exception->getMessage(),'data'=>[]];
         }
     }


    /**
     * 获取成品详情
     */
     public function getFinishProductInfoRep($id){
         $info = FinishProduct::where('id',$id)
             ->with(['order','stock_allocation_log'])
             ->first();
         return $info;
     }

    /**
     * 成品库扣款 / 取消扣款
     * @param $params
     * finish_product_id  成品id
     * is_deduct_money    1：扣款2取消扣款
     *
     */
     public function deductMoneyRep($params){
         $finish_product_id = $params['finish_product_id'];
         $model = FinishProduct::where('id',$finish_product_id)->with(['order'=>function($q){
             $q->select('id','receivables','received','customer_id');
         }])->first();
         $receivables = intval($model->order->receivables);//应收款
         $received = intval($model->order->received);//已收款
         $customer_id = $model->order->customer_id;
         $customer = Customer::where('id',$customer_id)->first();
         $balance = $customer->balance;//余额
         DB::beginTransaction();
         try{
             if($params['is_deduct_money'] == 1){
                 //扣款
                 $after = $balance - ($receivables - $received);
                 $business = '扣款';
                 $model->is_deduct_money = 1;
             }else{
                 //取消扣款
                 $after = $balance + ($receivables - $received);
                 $business = '取消扣款';
                 $model->is_deduct_money = 2;
             }
             $model->save();
             //添加资金变动记录
             $balanceHistoryRep = new BalanceHistoryRep();
             $balanceHistoryRep->addBalanceHistoryRep($customer_id,$receivables,$balance,$after,$model->order_id,$business,$detail='');
             //修改余额
             $customer->balance = $balance - ($receivables - $received);
             $customer->save();

             DB::commit();
             return ['code'=>0,'msg'=>'success','data'=>[]];
         }catch(\Exception $exception){
             DB::rollBack();
             return ['code'=>2001,'msg'=>$exception->getMessage(),'data'=>[]];
         }

     }
     public function updateFinishProductNumRep($params){
         $model = FinishProduct::where('id',$params['id'])->first();
         $model->num = $params['num'];
         $model->save();
         return $model;
     }



    /**
     * 删除成品
     * @param $params
     */
     public function delFinishProductRep($params){
         $finish_product_id = $params['finish_product_id'];
         $model = FinishProduct::where('id',$finish_product_id)->first();
         $model->is_del = 1;
         $model->save();
         return $model;
     }

    /**
     * 扫码盘点
     * @param $params
     */
    public function scanQRCodesCheckRep($params){
        DB::beginTransaction();
        try{
            $finish_product = FinishProduct::where('order_id',$params['order_id'])->first();
            $check_log = new CheckLog();

            $check_log->order_id = $finish_product->order_id;
            $check_log->user_id = $params['user_id'];
            $check_log->check_time = date("Y-m-d H:i:s");
            $check_log->warehouse_id = $params['warehouse_id'];
            $check_log->goods_shelf_id = $params['goods_shelf_id'];
            $check_log->before_num = $finish_product->num;
            $check_log->after_num = $params['after_num'];
            $check_log->save();


            $finish_product->warehouse_id = $params['warehouse_id'];
            $finish_product->goods_shelf_id = $params['goods_shelf_id'];
            //物流状态1：待发货2未发货3已发货4部分待发货5部分未发货
            $logistics_status = $finish_product->logistics_status;
            if(in_array($logistics_status,[1,2,4])){
                if($finish_product->num > $params['after_num']){
                    //盘点数小于订单数
                    if($logistics_status == 2){
                        $finish_product->num = $params['after_num'];
                    }else{
                        $finish_product->num = $params['after_num'];
                        OrderLogistics::where('order_id',$finish_product->order_id)->delete();
                        $finish_product->logistics_status = 1;
                        //添加发货记录
                        $orderLogisticsRep = new OrderLogisticsRep();
                        $remark = '盘点设置代发货';
                        $orderLogistics = $orderLogisticsRep->addOrderLogistics($finish_product->id,$finish_product->order_id,3,$params['after_num'],$remark);
                    }
                }elseif($finish_product->num < $params['after_num']){
                    //盘点数大于订单数
                    $finish_product->num = $params['after_num'];
                    if($logistics_status == 1){
                        $finish_product->logistics_status = 4;
                    }
                }
            }else{
                $finish_product->logistics_status = 2;
                $finish_product->num = $params['after_num'];
            }
            $finish_product->is_check = 1;
            $finish_product->check_time = date("Y-m-d");
            $finish_product->save();
            DB::commit();
            return ['code'=>0,'msg'=>'success','data'=>$finish_product];
        }catch (\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'msg'=>$exception->getMessage(),'data'=>[]];
        }



    }


    /**
     * 修改成品所属仓库货架
     * @param $params
     */
    public function alterFinishProductWarehouseRep($params){
        $model = FinishProduct::where('id',$params['finish_product_id'])->first();
        $model->warehouse_id = $params['warehouse_id'];
        $model->goods_shelf_id = $params['goods_shelf_id'];
        $model->save();
        return $model;
    }




}
